package com.chen.nongansampling.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProviders;

import com.chen.nongansampling.R;
import com.chen.nongansampling.adapter.LabelPrintAdapter;
import com.chen.nongansampling.app.BaseApplication;
import com.chen.nongansampling.bean.qrcode.FormatBySamplingBean;
import com.chen.nongansampling.bean.qrcode.QRcodeCallback;
import com.chen.nongansampling.bean.qrcode.QRcodeRequest;
import com.chen.nongansampling.newdayin.newDayin;
import com.chen.nongansampling.presenter.LabelPrintedPresenter;
import com.chen.nongansampling.presenterView.LabelPrintedView;
import com.chen.nongansampling.utils.QRCodeUtil;
import com.chen.nongansampling.viewModel.SamplingViewModel;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.chen.nongansampling.MainActivity.cunchu;
import static com.chen.nongansampling.MainActivity.yx;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link LabelPrintedFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class LabelPrintedFragment extends Fragment implements LabelPrintedView {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static Context mContext;
    public static Bitmap qrcode_bitmap;
    public Context huoquconment(){
        return getContext();
    }
    public  LabelPrintedFragment(Context context){
        this.mContext=context;
        }

    @BindView(R.id.sample_number)
    TextView sampleNumber;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private String urlchuan;
    private String idchuan;
    private OnFragmentInteractionListener mListener;
    private LabelPrintedPresenter labelPrintedPresenter = new LabelPrintedPresenter(getContext());
    public static FragmentActivity activity;
    private List<String> list = new ArrayList<>();
    private String left[] = {"样品名称", "采样时间", "经营户", "摊位号", "市场名称", "检测项目", "检测方法", "检测结果", "检测时间"};//假数据
    private String right[] = {"蒜苗", "2020-3-17", "陈飞旭", "1D13", "越秀菜市场", "氨基甲酸酯类", "酶抑制法", "阴性", "2020-02-18"};//假数据


    @OnClick(R.id.back_to_sample)
    public void onClick() {
        TextView title = getActivity().findViewById(R.id.sample_tool_bar_name);
        title.setText("已采样");
        getActivity().getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, SampledFragment.newInstance())
                .commitNow();


    }

    @OnClick(R.id.wrap_content)
    public void onClickdayin() {



    }

    public LabelPrintedFragment() {

    }

    public FragmentActivity fanhuiactiity(){
       return activity;
    }

    public static LabelPrintedFragment newInstance() {
        return new LabelPrintedFragment();
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment LabelPrintedFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static LabelPrintedFragment newInstance(String param1, String param2) {
        LabelPrintedFragment fragment = new LabelPrintedFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @OnClick(R.id.back_to_sample_quanbu)
    public void onClicks(View view) {

      cunchu.setKEY(4);
      cunchu.setBiaoshi(1);
        getFragmentManager().popBackStack();
        //注册
    }
    @OnClick(R.id.dayin)
    public void onClick(View view) {

        Intent intent= new Intent();
        intent.setClass(mContext, newDayin.class);
        activity=getActivity();
        intent.putExtra("list", right);
        intent.putExtra("url", urlchuan);
        intent.putExtra("id", idchuan);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);

        //注册
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }



    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.fragment_label_printed, container, false);
        Button jixu =  view.findViewById(R.id.back_to_sample_quanbu);
        if(yx==false){
            jixu.setVisibility(View.GONE);
        }else{
            jixu.setVisibility(View.VISIBLE);
        }
        TextView textView = (TextView) getActivity().findViewById(R.id.sample_tool_bar_name);
        // textView.setText("");

        ButterKnife.bind(this, view);
        return view;
    }

    @BindView(R.id.label_printed_listview)
    ListView ls;



    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        //   generateQrcodeAndDisplay();

    //    initAdapter();

        labelPrintedPresenter.BindPresentView(this);
        SamplingViewModel model = ViewModelProviders.of(getActivity()).get(SamplingViewModel.class);


        QRcodeRequest qRcodeRequest = new QRcodeRequest();
        qRcodeRequest.setAccountPkId(BaseApplication.account.getPkId());
        qRcodeRequest.setSamplingPkId(model.getSamplingPkId());
        labelPrintedPresenter.getUrlBySamplingPkId(qRcodeRequest);
        labelPrintedPresenter.getFormatBySamplingPkIdReseponseInfo(qRcodeRequest);
        initToolbar();
    }


    public void initToolbar() {
        Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
//        getActivity().setSupportActionBar(toolbar);
//        getSupportActionBar().setDisplayShowTitleEnabled(false);//隐藏标题
        toolbar.setNavigationIcon(R.mipmap.back_white);       //加载图标
        toolbar.setTitle("");
        TextView title = getActivity().findViewById(R.id.sample_tool_bar_name);
        title.setText("标签打印");
        title.setGravity(Gravity.CENTER);
        //     toolbar.setOverflowIcon(ContextCompat.getDrawable(getContext(),R.mipmap.add_sample));

        ImageButton imageButton = getActivity().findViewById(R.id.add_sample);
        imageButton.setVisibility(View.INVISIBLE);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {   //为图标设置监听器
            @Override
            public void onClick(View v) {


                getActivity().onBackPressed();

            }
        });

        toolbar.setNavigationIcon(R.mipmap.back_white);       //加载图标
    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

//    @Override
//    public void onAttach(Context context) {
//        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
//    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onError(String result) {

    }

    @Override
    public void onSuccess(Object resultData) {

        QRcodeCallback qRcodeCallback = (QRcodeCallback) resultData;


        Log.d("QRcodeCallback", resultData.toString());

        generateQrcodeAndDisplay(qRcodeCallback.getUrl());
 //       sampleNumber.setText();


    }


//    private String left[] = {"样品名称", "采样时间", "经营户", "摊位号", "市场名称", "检测项目", "检测方法", "检测结果", "检测时间"};//假数据


    @Override
    public void getFormatBySamplingPkIdReseponseInfo(FormatBySamplingBean callback) {
        FormatBySamplingBean bean=callback;
        if (bean.getSamplingName()!=null)
        right[0]=bean.getSamplingName();
        right[1]=bean.getSamplingTime();

        right[2]=bean.getOperatingHouseholds();

        right[3]=bean.getBoothNumber();

        right[4]=bean.getShichang();

        right[5]=bean.getDeListBeans().get(0).getType();

        right[6]=bean.getDeListBeans().get(0).getMethod();
        right[7]=bean.getDeListBeans().get(0).getResult();


        right[8]=bean.getDeListBeans().get(0).getDateTime();
        sampleNumber.setText(bean.getSampleNumber());
        idchuan=bean.getSampleNumber();
        Log.d("1111111111111111", bean.toString());
        LabelPrintAdapter labelPrintAdapter = new LabelPrintAdapter(Arrays.asList(left), Arrays.asList(right), getContext());
        ls.setAdapter(labelPrintAdapter);



    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }


    private void generateQrcodeAndDisplay(String url) {
//        content = et_content.getText().toString();
//        String str_width = et_width.getText().toString();
//        String str_height = et_height.getText().toString();
//        if (str_width.length() <= 0 || str_height.length() <= 0) {
//            width = 650;
//            height = 650;
//        } else {
//            width = Integer.parseInt(str_width);
//            height = Integer.parseInt(str_height);
//        }
//
//        if (content.length() <= 0) {
//            Toast.makeText(this, "你没有输入二维码内容哟！", Toast.LENGTH_SHORT).show();
//            return;
//        }
//        QRCodeUtil  qrcode_bitmap = QRCodeUtil.createQRCodeBitmap("www.baidu.com" , 500, 500, "UTF-8",
//                "H"  , "1", Color.BLACK, Color.WHITE);
        float a = 0;
        ImageView qrCode = getActivity().findViewById(R.id.qr_code);
        qrcode_bitmap = QRCodeUtil.createQRCodeBitmap(url, 1000, 1000, "UTF-8", "H", "1", Color.BLACK, Color.WHITE, null, a, null);
        urlchuan=url;
        qrCode.setImageBitmap(qrcode_bitmap);

    }

}
